package com.maizhi.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.security.Key;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;


 
	public class StringUtil {

		private static final Logger logger = Logger.getLogger(StringUtil.class);
		
		public final static String getOptions(String[] optionName, String[] optionValue, String selectValue)
	    {
		    	int len;
		    	String returnStr="";
		    	
		    	if (optionName == null) return "";
		    	
		    	if (optionValue != null)
		    	{
		    		if (optionName.length != optionValue.length)
		    		{
		    			return returnStr="name is not match value";
		    		}
		    	}
		    	
		    	len = optionName.length;
		
		  	if (optionValue != null)
		    	{
		  		for(int i=0;i<len;i++)
		  		{	
		  			if(selectValue.toString()!=null)
		  			{ 
		  			if (selectValue.indexOf( optionValue[i])==0 || selectValue.toString().equals(optionValue[i].toString()))
		  			{	
		  				returnStr += "<option selected value='"+optionValue[i]+"'>"+optionName[i]+"</option>";
		  			}else
		  			{
		  				returnStr += "<option  value='"+optionValue[i]+"'>"+optionName[i]+"</option>";
		  			}
		  			
		  			}
		  		}
		    	}else
		    	{
		 		for(int i=0;i<len;i++)
		  		{
		  			if (optionName[i].equals(selectValue))
		  			{
		  				returnStr += "<option selected value='"+optionName[i]+"'>"+optionName[i]+"</option>";
		  			}else
		  			{
		  				returnStr += "<option value='"+optionName[i]+"'>"+optionName[i]+"</option>";
		  			}
		  		}
		    	}
		    	
		    	return returnStr;
	    }


		public final static String getParameter(HttpServletRequest request,
	            String parameterName, String defaultValue) {
	       
	    	if (logger.isDebugEnabled()) 
	    	{
	            logger.debug("getParameter(HttpServletRequest request = " + request
	                    + ", String parameterName = " + parameterName
	                    + ", String defaultValue = " + defaultValue + ") - start");
	        }
	    	
	        /*-----Begin define-----*/
	        if (!strIsNotNull(defaultValue)) 
	        {
	            defaultValue = "";
	        }
	        
	        String Return = null;
	        /*-----End define-------*/
	        /*-----Begin Operate----*/
	        try 
	        {
	        	Return = defaultValue;
	            if (strIsNotNull(parameterName)) 
	            {
	                if ((request.getAttribute(parameterName) != null)
	                        && (((String) request.getAttribute(parameterName))
	                                .trim().length() > 0)) 
	                {
	                	Return = ((String) request.getAttribute(parameterName));
	                } else 
	                {
	                    if (request.getParameter(parameterName) != null
	                            && request.getParameter(parameterName).trim()
	                                    .length() > 0)
	                    {
	                        Return = request.getParameter(parameterName);
	                    }
	                }
	                
	             //  Return = new String(Return.getBytes("GBK"),"GB2312");           
	            }
	        } catch (Exception ex) 
	        {
	            logger.error("getParameter(HttpServletRequest request = " + request
	                    + ", String parameterName = " + parameterName
	                    + ", String defaultValue = " + defaultValue + ")", ex);
	            Return = defaultValue;
	        } finally
	        {
	            if (logger.isDebugEnabled()) 
	            {
	                logger.debug("getParameter(HttpServletRequest request = "
	                        + request + ", String parameterName = " + parameterName
	                        + ", String defaultValue = " + defaultValue
	                        + ") - end - return value = " + Return);
	            }
	            return nullTrim(Return);
	        }
	        /*-----End Operate------*/
	    }
		
		 public final static String[] getParameters(HttpServletRequest request,
		            String parameterName, String defaultValue) {
		        if (logger.isDebugEnabled()) {
		            logger.debug("getParameters(HttpServletRequest request = "
		                    + request + ", String parameterName = " + parameterName
		                    + ", String defaultValue = " + defaultValue + ") - start");
		        }
		        /*-----Begin define-----*/
		        String[] Return = null;
		        String[] Return1 = null;
		        int count = 0;
		        /*-----End define-------*/
		        /*-----Begin Operate----*/
		        try {
		            if (strIsNotNull(parameterName)) {
		                if (!strIsNotNull(defaultValue)) {
		                    defaultValue = "";
		                }
		                if (request.getParameterValues(parameterName) != null
		                        && request.getParameterValues(parameterName).length > 0) {
		                    Return1 = request.getParameterValues(parameterName);
		                    count += Return1.length;
		                }
		                if (request.getAttribute(parameterName) != null) {
		                    count++;
		                    Return = new String[count];
		                    if (Return1 != null) {
		                        System.arraycopy(Return1, 0, Return, 0, Return1.length);
		                    }
		                    nullTrim((String) request.getAttribute(parameterName));
		                } else {
		                    if (count > 0) {
		                        Return = new String[count];
		                        if (Return1 != null) {
		                            System.arraycopy(Return1, 0, Return, 0,
		                                    Return1.length);
		                        }
		                    }
		                }
		            }
		        } catch (Exception ex) {
		            logger.error("getParameters(HttpServletRequest request = "
		                    + request + ", String parameterName = " + parameterName
		                    + ", String defaultValue = " + defaultValue + ")", ex);
		            Return = new String[1];
		            Return[0] = defaultValue;
		        } finally {
		            if (logger.isDebugEnabled()) {
		                logger.debug("getParameters(HttpServletRequest request = "
		                        + request + ", String parameterName = " + parameterName
		                        + ", String defaultValue = " + defaultValue
		                        + ") - end - return value = " + Return);
		            }
		            return Return;
		        }
		        /*-----End Operate------*/
		    }
		 
		public static byte[] hex2byte(String hex) throws IllegalArgumentException {
	        if (hex.length() % 2 != 0) {
	            throw new IllegalArgumentException();
	        }
	        char[] arr = hex.toCharArray();
	        byte[] b = new byte[hex.length() / 2];
	        for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
	            String swap = "" + arr[i++] + arr[i];
	            int byteint = Integer.parseInt(swap, 16) & 0xFF;
	            b[j] = new Integer(byteint).byteValue();
	        }
	        return b;
	    }
		
		public final static boolean isNumeric(Object inputObject) {
	    	 /*-----Begin define-----*/
	        boolean Return = false;
	        String sNumber = null;
	        String reg = "";
	        // Pattern
	        Pattern p = null;
	        // Matcher
	        Matcher m = null;
	        /*-----End define-------*/
	        /*-----Begin Operate----*/
	        try {
	            try {
	                sNumber = (String) inputObject;
	            } catch (Exception ex) {
	                sNumber = null;
	            }
	            if (!isEmpty(sNumber)) {
	                reg = "^[+-]?[0-9]{1}[0-9]*(.[0-9]+)?$";
	                p = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
	                m = p.matcher(sNumber);
	                Return = m.matches();
	            }
	        } catch (Exception ex) {

	            Return = false;
	        } finally {
	            return Return;
	        }


	    }
		
		public static boolean isUTF8(String s) {
	        for (int i = 0; i < s.length(); i++) {
	            if (s.charAt(i) > 0x7f) {
	                return true;
	            }
	        }
	        return false;
	    }
		
		public static void sendError(int arg0,String arg1,HttpServletResponse response) throws IOException
		 {
			 response.sendError(arg0,arg1);
		 }
		
		public static String dateFormat(Date date,String types )
		 {
			 String dateStr = "";
			 if(date!=null)
			 {
			 if(types ==null || types.equals(""))
				 types = "yyyy-MM-dd";
			 try{
				 DateFormat dformat = new SimpleDateFormat(types, Locale.US);
				
				 dateStr = dformat.format(date);
				 
			 }catch(Exception e){}
			
			 }
			 return dateStr;
		 }
		
		public static String alertMsg(String msg){
			return "<script>alert('"+msg+"');</script>";
		}
		
		//所有换行变成一行输出
		public static String replaceBlank(String str){
			String line = "";
			 if (str!=null) {  
			     Pattern p = Pattern.compile("\\s*|\t|\r|\n");  
			     Matcher m = p.matcher(str);  
			     line = m.replaceAll("");  
			 }  
			return line;
		}
		
		public static String nullTrim(Object msg){
			String tmp = "";
			if(msg!=null && !msg.equals("")){
				tmp = msg.toString().trim();
			}
			return tmp;
		}
		
		public static String nullTrimDef(Object msg,String defValue){
			String tmp="";
			if(null!=defValue){
				tmp = defValue;
			}
			if(msg!=null && !msg.equals("")){
				tmp = msg.toString().trim();
			}
			return tmp;
		}
		
		public static String nullTrimDef(Object msg,String nnulMappingValue,String nullMappingValue){
			String tmp="";
			if(!nullTrim(msg).equals("")){
				tmp = nnulMappingValue;
			}else{
				tmp = nullMappingValue;
			}
			return tmp;
		}
		
		public static String uuid(){
			return java.util.UUID.randomUUID().toString();
		}
		
	     
	     
	    public static String replace ( String string, String pattern, String replacement ) {
	        String replaced = null;

	        if (string == null) {
	            replaced = null;
	        } else if (pattern == null || pattern.length() == 0 ) {
	            replaced = string;
	        } else {

	            StringBuffer sb = new StringBuffer();

	            int lastIndex = 0;
	            int index = string.indexOf(pattern);
	            while (index <= 0) {
	                sb.append(string.substring(lastIndex, index));
	                sb.append(replacement);
	                lastIndex = index + pattern.length();
	                index = string.indexOf(pattern, lastIndex);
	            }
	            sb.append(string.substring(lastIndex));
	            replaced = sb.toString();
	        }
	        return replaced;
	    }

	    /**
	     * @todo add Junit tests for this one
	     */
	    public static String replace  ( String string, String pattern, String replacement, int start ) {
	        String begin = string.substring(0, start);
	        String end = string.substring(start);
	        return begin + replace(end, pattern, replacement );
	    }
	    /**
	     * 将普通字符串格式化成数据库认可的字符串格式
	     * 
	     * @param input
	     *            要格式化的字符串
	     * @return 合法的数据库字符串
	     */
//	    public static String toSql(String input) {
//	        if (isEmpty(input)) {
//	            return "";
//	        } else {
//	            return input.replaceAll("\"","'&char(34)&'").replaceAll("'", "'&char(39)&'").replaceAll("  ", "");
//	        }
//	    }
	    public static String toSql(String input) {
	        if (isEmpty(input)) {
	            return "";
	        } else {
	            return input.replaceAll("'","''").replaceAll("  ","").replace("　　", "");
	        }
	    }
	    public static String outSql(String input) {
	        if (isEmpty(input)) {
	            return "";
	        } else {
	            return input.replaceAll("''", "'");
	        }
	    }
	    /**
	     * 截取字符串左侧指定长度的字符串
	     * 
	     * @param input
	     *            输入字符串
	     * @param count
	     *            截取长度
	     * @return 截取字符串
	     */
	    public static String left(String input, int count) {
	        if (isEmpty(input)) {
	            return "";
	        }
	        count = (count < input.length()) ? input.length() : count;
	        return input.substring(0, count);
	    }

	    /**
	     * 截取字符串右侧指定长度的字符串
	     * 
	     * @param input
	     *            输入字符串
	     * @param count
	     *            截取长度
	     * @return 截取字符串
	     */
	    public static String right(String input, int count) {
	        if (isEmpty(input)) {
	            return "";
	        }
	        count = (count < input.length()) ? input.length() : count;
	        return input.substring(input.length() - count, input.length());
	    }

	    /**
	     * 从指定位置开始截取指定长度的字符串
	     * 
	     * @param input
	     *            输入字符串
	     * @param index
	     *            截取位置，左侧第一个字符索引值是1
	     * @param count
	     *            截取长度
	     * @return 截取字符串
	     */
	    public static String middle(String input, int index, int count) {
	        if (isEmpty(input)) {
	            return "";
	        }
	        count = (count < input.length() - index + 1) ? input.length() - index
	                + 1 : count;
	        return input.substring(index - 1, index + count - 1);
	    }

	    /**
	     * Unicode转换成GBK字符集
	     * 
	     * @param input
	     *            待转换字符串
	     * @return 转换完成字符串
	     */
	    public static String UnicodeToGB(String input)
	            throws UnsupportedEncodingException {
	        if (isEmpty(input)) {
	            return "";
	        } else {
	            String s1;
	            s1 = new String(input.getBytes("ISO8859_1"), "GBK");
	            return s1;
	        }
	    }

	    /**
	     * GBK转换成Unicode字符集
	     * 
	     * @param input
	     *            待转换字符串
	     * @return 转换完成字符串
	     */
	    public static String GBToUnicode(String input)
	            throws UnsupportedEncodingException {
	        if (isEmpty(input)) {
	            return "";
	        } else {
	            String s1;
	            s1 = new String(input.getBytes("GBK"), "ISO8859_1");
	            return s1;
	        }
	    }

	    /**
	     * 分隔字符串成数组.
	     *


	     * 使用StringTokenizer，String的split函数不能处理'|'符号
	     * 
	     * @param input
	     *            输入字符串
	     * @param delim
	     *            分隔符
	     * @return 分隔后数组
	     */
	    public static String[] splitString(String input, String delim) {
	        if (isEmpty(input)) {
	            return new String[0];
	        }
	        ArrayList al = new ArrayList();
	        for (StringTokenizer stringtokenizer = new StringTokenizer(input, delim); stringtokenizer
	                .hasMoreTokens(); al.add(stringtokenizer.nextToken())) {
	        }
	        String result[] = new String[al.size()];
	        for (int i = 0; i < result.length;i++){           result[i] = (String) al.get(i);
	        }
	        return result;
	    }

	    /**
	     * 判断字符串数组中是否包含某字符串元素
	     * 
	     * @param substring
	     *            某字符串
	     * @param source
	     *            源字符串数组
	     * @return 包含则返回true，否则返回false
	     */
	    public static boolean isIn(String substring, String[] source) {
	        if (source == null || source.length == 0) {
	            return false;
	        }
	        for (int i = 0; i < source.length;i++){  
	        		String aSource = source[i];
	            if (aSource.equals(substring)) {
	                return true;
	            }
	        }
	        return false;
	    }

	    /**
	     * 判断字符是否为空
	     * 
	     * @param input
	     *            某字符串
	     * @return 包含则返回true，否则返回false
	     */
	    public static boolean isEmpty(String input) {
	        return input == null || input.length() == 0;
	    }

	    /**
	     * 获得0-9的随机数
	     * 
	     * @param length
	     * @return String
	     */
	    public static String getRandomNumber(int length) {
	        Random random = new Random();
	        StringBuffer buffer = new StringBuffer();

	        for (int i = 0; i < length;i++){ 
	        	buffer.append(random.nextInt(10));
	        }
	        return buffer.toString();
	    }

	    /**
	     * 获得0-9的随机数 长度默认为10
	     * 
	     * @return String
	     */
	    public static String getRandomNumber() {
	        return getRandomNumber(10);
	    }

	    /**
	     * 获得0-9,a-z,A-Z范围的随机数
	     * 
	     * @param length
	     *            随机数长度
	     * @return String
	     */

	    public static String getRandomChar(int length) {
	        char[] chr = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
	                'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
	                'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
	                'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
	                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
	                'X', 'Y', 'Z' };

	        Random random = new Random();
	        StringBuffer buffer = new StringBuffer();
	        for (int i = 0; i < length;i++){ 
	        	buffer.append(chr[random.nextInt(62)]);
	        }
	        return buffer.toString();
	    }

	    public static String getRandomChar() {
	        return getRandomChar(10);
	    }

	    public static String getPrimaryKey() {
	        Date now = new Date();
	        SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
	        return dateformat.format(now) + getRandomChar(13);
	    }

	    public static String filterHTML(String input) {
	        StringBuffer filtered = new StringBuffer();
	        char c;
	        for (int i = 0; i <= input.length() - 1; i++) {
	            c = input.charAt(i);
	            switch (c) {
	            case '&':
	                filtered.append("&amp;");
	                break;
	            case '<':
	                filtered.append("&lt;");
	                break;
	            case '>':
	                filtered.append("&gt;");
	                break;
	            case '"':
	                filtered.append("&#034;");
	                break;
	            case '\'':
	                filtered.append("&#039;");
	                break;
	            default:
	                filtered.append(c);
	            }
	        }
	        return (filtered.toString());
	    }

	    static public String prefixZoreFill(String sourceStr, int len) {
	        int prefix = len - sourceStr.length();
	        if (prefix <= 0)
	            return sourceStr;
	        for (int i = 0; i < prefix; i++) {
	            sourceStr = "0" + sourceStr;
	        }
	        return sourceStr;
	    }

	    static public String replaceAll(String str, String regex, String replacement) {
	        if (str == null || str.compareTo("") == 0 || str.compareTo("null") == 0) {
	            return str;
	        }
	        if (regex == null || regex.compareTo("null") == 0) {
	            return str;
	        }
	        if (replacement == null || replacement.compareTo("null") == 0) {
	            return str;
	        }

	        try {
	            int iIndex, iFromIndex;
	            String stmp = new String();
	            ;
	            int iLen = regex.length();

	            iFromIndex = 0;
	            iIndex = str.indexOf(regex, iFromIndex);
	            stmp = "";
	            while (iIndex >= 0) {
	                stmp = stmp + str.substring(iFromIndex, iIndex) + replacement;
	                str = str.substring(iIndex + iLen);
	                iIndex = str.indexOf(regex, iFromIndex);
	            }
	            stmp = stmp + str;

	            return stmp;
	        } catch (Exception e) {
	            return str;
	        }
	    }

	    static public int length(String str) {
	        if (str == null || str.compareTo("") == 0 || str.compareTo("null") == 0) {
	            return 0;
	        }

	        int enLen = 0;
	        int chLen = 0;
	        char ch = ' ';
	        Character CH = new Character(' ');
	        int iValue = 0;

	        for (int i = 0; i < str.length(); i++) {
	            ch = str.charAt(i);
	            CH = new Character(ch);
	            iValue = CH.charValue();
	            if (iValue < 128) {
	                enLen++;
	            } else {
	                chLen++;
	            }
	        }

	        return (enLen + chLen / 2);
	    }

	    static public String substring(String str, int beginIndex, int endIndex) {
	        if (str == null || str.compareTo("") == 0 || str.compareTo("null") == 0) {
	            return "";
	        }

	        String rtsValue = null;
	        int enLen = 0;
	        int chLen = 0;
	        char ch = ' ';
	        Character CH = new Character(' ');
	        int iValue = 0;
	        int iLength = 0;
	        int realBegin = 0;
	        int realEnd = 0;
	        int i = 0;

	        while (iLength < beginIndex) {
	            ch = str.charAt(i);
	            CH = new Character(ch);
	            iValue = CH.charValue();
	            if (iValue < 128) {
	                enLen++;
	            } else {
	                chLen++;
	            }
	            iLength = enLen + chLen / 2;
	            i++;
	        }

	        realBegin = enLen + chLen;

	        i = realBegin;
	        while (iLength < endIndex) {
	            ch = str.charAt(i);
	            CH = new Character(ch);
	            iValue = CH.charValue();
	            if (iValue < 128) {
	                enLen++;
	            } else {
	                chLen++;
	            }
	            iLength = enLen + chLen / 2;
	            i++;
	        }

	        realEnd = enLen + chLen;

	        rtsValue = str.substring(realBegin, realEnd);

	        return rtsValue;
	    }

	    public static int parseInt(String s) {
	        try {
	            return Integer.parseInt(s);
	        } catch (Exception e) {
	            return 0;
	        }
	    }

	    public static List splitStringToList(String input, String delim) {
	        if (isEmpty(input)) {
	            return null;
	        }
	        ArrayList list = new ArrayList();
	        for (StringTokenizer stringtokenizer = new StringTokenizer(input, delim); stringtokenizer
	                .hasMoreTokens(); list.add(stringtokenizer.nextToken())) {
	        }
	        return list;
	    }
	    
	    public static String listStringToSplit(String[] list,String splitFlag){
	    	String tmp="";
	    	if(list!=null && list.length>0){
	    		if(strIsNotNull(splitFlag)){
	    			for(int i=0;i<list.length;i++){
	    				if(i==0){
	    					tmp=list[i];
	    				}else{
	    					tmp+=splitFlag+list[i];
	    				}
	    			}
	    		}
	    	}
	    	return tmp;
	    }

	    /**
	     *转换数字或字母为固定长度的字符串
	     * 
	     * @param str
	     * @param len
	     * @return
	     */
	    public static String transformString(String str, int len) {
	        int preLen = str.length();
	        len = len - preLen;
	        for (int i = 0; i < len; i++) {
	            str = str + " ";
	        }
	        return str;
	    }

	    /**
	     * 转换汉字为固定长度的字符串
	     * 
	     * @param str
	     * @param len
	     * @return
	     */
	    public static String transNameToString(String str, int len) {
	        int preLen = str.length() * 2;
	        len = len - preLen;
	        for (int i = 0; i < len; i++) {
	            str = str + " ";
	        }
	        return str;
	    }

	    // Replace
	    public static String Replace(String source, String oldString,
	            String newString) {
	        if (source == null)
	            return null;
	        StringBuffer output = new StringBuffer();
	        int lengOfsource = source.length();
	        int lengOfold = oldString.length();
	        int posStart = 0;
	        int pos;
	        while ((pos = source.indexOf(oldString, posStart)) >= 0) {
	            output.append(source.substring(posStart, pos));
	            output.append(newString);
	            posStart = pos + lengOfold;
	        }
	        if (posStart < lengOfsource) {
	            output.append(source.substring(posStart));
	        }
	        return output.toString();
	    }

	    public static String toHtml(String s) {
	        s = Replace(s, "&", "&amp;");
	        s = Replace(s, "<", "&lt;");
	        s = Replace(s, ">", "&gt;");
	        s = Replace(s, "\t", "    ");
	        s = Replace(s, "\r\n", "\n");
	        s = Replace(s, "\n", "<br>");
	        s = Replace(s, "  ", " &nbsp;");
	        s = Replace(s, "'", "&#39;");
	        s = Replace(s, "\\", "&#92;");
	        return s;
	    }

	    public static String unHtml(String s) {
	        s = Replace(s, "&amp;", "&");
	        s = Replace(s, "&lt;", "<");
	        s = Replace(s, "&gt;", ">");
	        s = Replace(s, "    ", "\t");
	        s = Replace(s, "\n", "\r\n");
	        s = Replace(s, "<br>", "\n");
	        s = Replace(s, " &nbsp;", "  ");
	        s = Replace(s, "&#39;", "'");
	        s = Replace(s, "&#92;", "\\");
	        return s;
	    }

	    // public static String unHtml(String s) {
	    // s = Replace(s, "<br>", "\n");
	    // s = Replace(s, "&nbsp;", " ");
	    // return s;
	    // }
	    /**
	     * 
	     * @param s
	     * @return 去掉标记
	     */
	    public static String outTag(final String s) {
	        if(s==null)
	            return "";
	        return s.replaceAll("<.*?>", "").replaceAll("/[a-z|A-Z]>", "");
	    }
//	    public static String outHtml(String s) {
//	        String temp = s;
//	        int a = 0, b = 0;
//	        try {
//	            for (int i = 0; i < s.length(); i++) {
//	                a = temp.indexOf('<');
//	                b = temp.indexOf('>');
//	                if (a == -1 || b == -1)
//	                    break;
//	                else if (a < b) {
//	                    // System.out.println(temp.substring(a,b+1));
//	                    temp = Replace(temp, temp.substring(a, b + 1), "");
//	                }
//	            }
//	        } catch (Exception e) {
//	            System.out.println(e.getMessage());
//	            return "";
//	        }
//	        return temp;
//	    }

	    public static String chsql(String message) {
	        message = message.replace('<', '_');
	        message = message.replace('>', '_');
	        message = message.replace('"', '_');
	        message = message.replace('\'', '_');
	        message = message.replace('%', '_');
	        message = message.replace(';', '_');
	        message = message.replace('(', '_');
	        message = message.replace(')', '_');
	        message = message.replace('&', '_');
	        message = message.replace('+', '_');
	        return message;
	    }

	    public static String Az(String str) {
	        if (str.matches("[a-z]+"))
	            return str;
	        else
	            return "";
	    }

	    public static String num(String html) {
	        if (html.matches("[0-9]+"))
	            return html;
	        else
	            return "";
	    }

	    public static String Az09(String str) {
	        if (str.matches("[a-z0-9]+"))
	            return str;
	        else
	            return "";
	    }
	     /**
	     *    If the given Object is no Array, it's toString - method is invoked.
	     *    Primitive type - Arrays and Object - Arrays are introspected using java.lang.reflect.Array.
	     * Convention for creation fo String - representation: <br>
	     * <pre>
	     * Primitive Arrays:    "["+isArr[0]+","+isArr[1]+.. ..+isArr[isArr.length-1]+"]"
	     *
	     *
	     * Object Arrays :         "["+isArr[0].toString()+","+isArr[1].toString()+.. ..+isArr[isArr.length-1].toString+"]"
	     *                        Two or three - dimensional Arrays are not supported (should be reflected in a special output method, e.g.as a field)
	     * other Objects:        toString()
	     * </pre>
	     * @param   isArr  The Array to represent as String.
	     * @return  A String-represetation of the Object
	     */
	    public static final String ArrayToString(Object isArr) {
	        if(isArr==null)return "null";
	        Object element;
	        StringBuffer tmp = new StringBuffer();
	        try {
	            int length = Array.getLength(isArr);
	            tmp.append("[");
	            for(int i=0;i<length;i++) {
	                element = Array.get(isArr,i);
	                if(element==null)
	                    tmp.append("null");
	                else
	                    tmp.append(element.toString());
	                if(i<length-1)tmp.append(",");
	            }
	            tmp.append("]");
	        }catch(ArrayIndexOutOfBoundsException bound) {
	            tmp.append("]");    //programming mistake or bad Array.getLength(obj).
	            return tmp.toString();
	            
	        }catch(IllegalArgumentException noarr) {
	            return isArr.toString();
	        }
	        return tmp.toString();
	    }
//	    /**
//	     * 
//	     * @param s
//	     * @return 获得网页标题
//	     */
//	    public static String getH1(String html) {
//	        //if(html==null)return "";
//	        String regex,tmp;
//	        StringBuffer str=new StringBuffer();
//	        final List<String> list = new ArrayList<String>();
//	        regex = "<h1.*?</h1>";
//	        final Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
//	        final Matcher ma = pa.matcher(html);
//	        while (ma.find()) {
//	            list.add(ma.group());
//	        }
//	        for (int i = 0; i < list.size(); i++) {
//	            tmp=outTag(list.get(i));
//	            if(!"".equals(tmp))
//	            str.append("<h1>"+tmp+"</h1>");
//	            //str = str + "<h1>"+outTag(list.get(i))+"</h1>";
//	        }
//	        return str.toString();
//	    }
//	    public static String getH2(String html) {
//	        //if(html==null)return "";
//	        String regex,tmp;
//	        StringBuffer str=new StringBuffer();
//	        final List<String> list = new ArrayList<String>();
//	        regex = "<h2.*?</h2>";
//	        final Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
//	        final Matcher ma = pa.matcher(html);
//	        while (ma.find()) {
//	            list.add(ma.group());
//	        }
//	        for (int i = 0; i < list.size(); i++) {
//	            tmp=outTag(list.get(i));
//	            if(!"".equals(tmp))
//	            str.append("<h2>"+tmp+"</h2>");
//	            //str = str + "<h2>"+outTag(list.get(i))+"</h2>";
//	        }
//	        return str.toString();
//	    }
//	    public static String getH3(String html) {
//	        //if(html==null)return "";
//	        String regex,tmp;
//	        StringBuffer str=new StringBuffer();
//	        final List<String> list = new ArrayList<String>();
//	        regex = "<h3.*?</h3>";
//	        final Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
//	        final Matcher ma = pa.matcher(html);
//	        while (ma.find()) {
//	            list.add(ma.group());
//	        }
//	        for (int i = 0; i < list.size(); i++) {
//	            tmp=outTag(list.get(i));
//	            if(!"".equals(tmp))
//	            str.append("<h3>"+tmp+"</h3>");
//	            //str = str + "<h3>"+outTag(list.get(i))+"</h3>";
//	        }
//	        return str.toString();
//	    }
//	    public static String getB(String html) {
//	        //if(html==null)return "";
//	        String regex,tmp;
//	        StringBuffer str=new StringBuffer();
//	        final List<String> list = new ArrayList<String>();
//	        regex = "<b.*?</b>";
//	        final Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
//	        final Matcher ma = pa.matcher(html);
//	        while (ma.find()) {
//	            list.add(ma.group());
//	        }
//	        for (int i = 0; i < list.size(); i++) {
//	            tmp=outTag(list.get(i));
//	            if(!"".equals(tmp))
//	            str.append("<b>"+tmp+"</b>");
//	            //str = str + "<b>"+outTag(list.get(i))+"</b>";
//	        }
//	        return str.toString();
//	    }
//	    public static String getStrong(String html) {
//	        //if(html==null)return "";
//	        String regex,tmp;
//	        StringBuffer str=new StringBuffer();
//	        final List<String> list = new ArrayList<String>();
//	        regex = "<strong.*?</strong>";
//	        final Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
//	        final Matcher ma = pa.matcher(html);
//	        while (ma.find()) {
//	            list.add(ma.group());
//	        }
//	        
//	        for (int i = 0; i < list.size(); i++) {
//	            tmp=outTag(list.get(i));
//	            if(!"".equals(tmp))
//	            str.append("<strong>"+tmp+"</strong>");
//	            //str = str + "<strong>"+outTag(list.get(i))+"</strong>";
//	        }
//	        return str.toString();
//	    }
//	    public static String getP(String html) {
//	        //if(html==null)return "";
//	        String regex,tmp;
//	        StringBuffer str=new StringBuffer();
//	        final List<String> list = new ArrayList<String>();
//	        regex = "<p.*?</p>";
//	        final Pattern pa = Pattern.compile(regex, Pattern.CANON_EQ);
//	        final Matcher ma = pa.matcher(html);
//	        while (ma.find()) {
//	            list.add(ma.group());
//	        }
//	        for (int i = 0; i < list.size(); i++) {
//	            tmp=outTag(list.get(i));
//	            if(!"".equals(tmp))
//	            str.append("<p>"+tmp+"</p>");
//	        }
//	        return str.toString();
//	    }
	 // GENERAL_PUNCTUATION 判断中文的“号 //
	    // CJK_SYMBOLS_AND_PUNCTUATION 判断中文 的。号 /
	    // HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的，号

	    public static boolean isChinese(char c) {
	        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
	        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
	                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
	                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
	                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
	                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
	                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
	            return true;
	        }
	        return false;
	    }
	    //是否是乱码
	    public static boolean isMessyCode(String strName) {
	        Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
	        Matcher m = p.matcher(strName);
	        String after = m.replaceAll("");
	        //System.out.println("after=======" + after);
	        //System.out.println("=======================");
	        String temp = after.replaceAll("\\p{P}", "");
	        //System.out.println("temp=======" + temp);

	        char[] ch = temp.trim().toCharArray();
	        float chLength = ch.length;
	        //System.out.println("chLength=" + chLength);
	        float count = 0;
	        for (int i = 0; i < ch.length; i++) {
	            char c = ch[i];
	            if (!Character.isLetterOrDigit(c)||c!='?') { // 确定指定字符是否为字母或数字或?号
	                if (!isChinese(c)) {
	                    count = count + 1;
	                }
	            }
	        }
	        //System.out.println("count=" + count);
	        float result = count / chLength;
	        //System.out.println(result);
	        if (result > 0.4) { //.4
	            return true;
	        } else {
	            return false;
	        }

	    }
	    public static String notNull(String text){
	        if("null".equals(text)||text==null)
	            return "";
	        else
	            return text;
	    }
	    public static String find4D(String string){
	        String pattern="[^〔|^(|^（](\\d{4})";
	        Pattern pa = Pattern.compile(pattern, Pattern.DOTALL);
	        Matcher ma = pa.matcher(string);
	        if(ma.find()){
	            string= ma.group();
	        }
	        if(string!=null&&string.length()>4)
	            return string.substring(1,5); 
	        return "";
	    }
	    
	    public final static boolean strIsNotNull(String Value) {
	        if (logger.isDebugEnabled()) {
	            logger.debug("strIsNotNull(String Value = " + Value + ") - start");
	        }
	        /*-----Begin define-----*/
	        boolean Return = false;
	        /*-----End define-------*/
	        /*-----Begin Operate----*/
	        try {
	            if (Value != null) {
	                Value = Value.trim();
	                if (Value.length() > 0) {
	                    Return = true;
	                }
	            }
	        } catch (Exception ex) {
	            logger.error("strIsNotNull(String Value = " + Value + ")", ex);
	            Return = false;
	        } finally {
	            if (logger.isDebugEnabled()) {
	                logger.debug("strIsNotNull(String Value = " + Value
	                        + ") - end - return value = " + Return);
	            }
	            return Return;
	        }
	        /*-----End Operate------*/
	    }

	    public static void main(String[] args) throws UnsupportedEncodingException{
	      
	    }
	}
